﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Panels;
using VAdvantage.Grids;
using VAdvantage.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using VAdvantage.Model;
using System.Data;
using VAdvantage.DataBase;
using System.Threading;
using VAdvantage.Utility;
using SL4PopupMenu;
using System.ComponentModel;
using System.Text;
using VAdvantage.Classes;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using System.Reflection;
using System.Collections;
using VAdvantage.Framework;

namespace VAdvantage.Apps
{
    public partial class VGridPanel : UserControl
    {
        private int PAGE_LIMIT = 5;
        private GridController _gridController = null;

        private Chart _newChart = null;
        private MChart _mchart = null;

        private Grid RootLayoutGrid = null;
        private VDataGrid dataGrid = null;
        private BusyIndicator busyIndiactor = null;

        private ViennaRoleCenter rolecenter = null;

        public VGridPanel()
        {
            InitializeComponent();
            CreatePanelMenu();
        }

        public VGridPanel(ViennaRoleCenter _rolecenter, bool visible)
            : this(visible)
        {
            rolecenter = _rolecenter;

            if (rolecenter.MaxValue >= 0)
                PAGE_LIMIT = rolecenter.MaxValue;

            CreatePanelMenu();

        }

        public VGridPanel(bool visible)
        {
            InitializeComponent();
            if (!visible)
                this.Visibility = System.Windows.Visibility.Collapsed;
        }


        public void SetGridController(GridController controller)
        {
            _gridController = controller;
        }

        ScrollViewer _scrollPanel = null;
        public void SetScrollPanel(ScrollViewer scrollPanel)
        {
            _scrollPanel = scrollPanel;

        }
        public void SetChart(Chart chart)
        {
            _newChart = chart;
        }

        public void SetMChart(MChart mchart)
        {
            _mchart = mchart;
        }

        public void SetRootLayoutGrid(Grid layout)
        {
            RootLayoutGrid = layout;
        }

        public void PanelData(Grid g, bool firstTime)
        {
            RootLayoutGrid = g;
            //FrameworkElement grid = GridExtensions.FindElement(g, 1, 0);
            if (firstTime)
            {
                Grid.SetRow(_gridController, 0);
                Grid.SetColumn(_gridController, 0);
                //Grid.SetRowSpan(d, 2);
                _gridController.Margin = new Thickness(0, 4, 0, 0);

                ContentGrid.Children.Add(_gridController);
            }
        }


        public void PanelData(Grid g)
        {
            PanelData(g, false);
        }

        public void AddControl(FrameworkElement elem)
        {
            Grid.SetRow(elem, 0);
            Grid.SetColumn(elem, 0);

            ContentGrid.Children.Add(elem);
        }

        public void AddControl(FrameworkElement elem, int r, int c)
        {
            Grid.SetRow(elem, r);
            Grid.SetColumn(elem, c);

            grid2.Children.Add(elem);
        }

        public void RemoveControl(FrameworkElement elem)
        {
            ContentGrid.Children.Remove(elem);
        }

        public void RemoveData()
        {
            ContentGrid.Children.Remove(_gridController);
        }

        public void SetPager(System.Collections.IEnumerable source)
        {
            //vPager.PageSize = 5;
            //vPager.Source = source;
        }

        public void SetHeader(string msg)
        {
            lblHeader.Content = msg;
        }

        private void vPager_PageIndexChanged(object sender, EventArgs e)
        {

        }

        private void vHeader_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

        }

        int _TotalPages = 0;
        public void SetTotalPage(int page)
        {
            int remainderPage = 0;
            if ((page % PAGE_LIMIT) > 0)
                remainderPage = 1;

            _TotalPages = (page / PAGE_LIMIT) + remainderPage;
            lblPage.Content = CurrentPage + "/" + _TotalPages;
        }

        private int CurrentPage = 1;

        private void bNext_Click(object sender, RoutedEventArgs e)
        {
            CurrentPage++;
            GridTab tab = _gridController.GetMTab();

            //int remainderPage = 0;
            //if ((tab.GetTotalRowCount() % PAGE_LIMIT) > 0)
            //    remainderPage = 1;
            //int TotalPages = (tab.GetTotalRowCount() / PAGE_LIMIT) + remainderPage;
            if (CurrentPage > _TotalPages)
            {
                CurrentPage--;
                return;
            }
            //txtPageNum.Text = CurrentPage.ToString();
            lblPage.Content = CurrentPage.ToString() + "/" + _TotalPages;
            tab.GetTableObj().SetCurrentPage(CurrentPage);

            _gridController.GetDataGrid(this, RootLayoutGrid, 0, PAGE_LIMIT, false, 0, false);

        }

        private void bPrev_Click(object sender, RoutedEventArgs e)
        {
            if (CurrentPage == 1)
                return;
            CurrentPage--;
            lblPage.Content = CurrentPage.ToString() + "/" + _TotalPages.ToString();
            GridTab tab = _gridController.GetMTab();
            tab.GetTableObj().SetCurrentPage(CurrentPage);

            _gridController.GetDataGrid(this, RootLayoutGrid, 0, PAGE_LIMIT, false, 0, false);
        }

        private void bEdit_Click(object sender, RoutedEventArgs e)
        {

        }

        MChart _charts = null;
        public void AddChart(MChart charts)
        {
            SetD_Chart_ID(charts.Get_ID());
            _charts = charts;
            BusyIndicator chartBusy = new BusyIndicator();
            chartBusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;
            AddControl(chartBusy);
            chartBusy.IsBusy = true;

            bool loadchart = false;

            Chart newChart = new Chart();
            newChart.Margin = new Thickness(0, 0, 0, 0);
            newChart.Tag = charts.Get_ID();
            newChart.BorderThickness = new Thickness(0);

            var pm1 = new PopupMenu();
            pm1.AddItem("Open Dashboard", EditSeries_Click);
            pm1.AddTrigger(TriggerTypes.RightClick, newChart);

            // Showing main menu
            pm1.Showing += (sender, e) =>
            {
                selectedChart = (Chart)sender;
            };

            //newChart.Title = charts.GetName();
            Grid.SetRow(newChart, 0);
            Grid.SetColumn(newChart, 0);

            ContentGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
            ContentGrid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
            grid2.Visibility = System.Windows.Visibility.Collapsed;
            //border1.BorderThickness = new Thickness(0);

            loadchart = true;

            while (!loadchart)
                Thread.Sleep(0);

            loadchart = false;


            ThreadPool.QueueUserWorkItem(delegate
            {
                AddSeriesToChart(newChart, charts, chartBusy);
                Dispatcher.BeginInvoke(delegate
                {
                    chartBusy.IsBusy = false;
                });
            });

        }

        Chart selectedChart;
        void EditSeries_Click(object sender, RoutedEventArgs e)
        {
            DashBoard db = new DashBoard();
            db.Show();
        }

        /// <summary>
        /// Chart Types to be used in the application
        /// </summary>
        enum enmChartType
        {
            Column = 1,
            Line = 2,
            Pie = 3,
            Bar = 4

        }


        DataPointSeries newSeries;
        private int univValue = 42;
        /// <summary>
        /// Add Series to Chart
        /// </summary>
        /// <param name="newChart">new chart to be added</param>
        /// <param name="chart">Chart from the database</param>
        private void AddSeriesToChart(Chart newChart, MChart chart, BusyIndicator chartBusy)
        {
            try
            {
                MSeries[] series = MSeries.Get(chart.Get_ID());

                string sql = "";
                for (int i = 0; i <= series.Length - 1; i++)
                {
                    univValue++;


                    bool loadseries = false;
                    Dispatcher.BeginInvoke(delegate
                    {
                        if (int.Parse(chart.GetChartType()) == (int)enmChartType.Bar)
                            newSeries = new BarSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Column)
                            newSeries = new ColumnSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Line)
                            newSeries = new LineSeries();
                        else if (int.Parse(chart.GetChartType()) == (int)enmChartType.Pie)
                            newSeries = new PieSeries();

                        newSeries.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                        newSeries.IndependentValuePath = "Key";
                        newSeries.DependentValuePath = "Value";
                        newSeries.Name = series[i].GetName();
                        newSeries.Tag = series[i].Get_ID();

                        loadseries = true;
                    });

                    while (!loadseries)
                        Thread.Sleep(10);

                    loadseries = false;

                    MPrintColor seriesColor = MPrintColor.Get(Envs.GetCtx(), series[i].GetAD_Series_Color_ID());

                    sql = series[i].GetSql(chart.IsShowZeroSeries(), "");
                    DataSet ds = DB.ExecuteDataset(sql, null);

                    if (ds.Tables[0].Rows.Count <= 25)
                    {
                        KeyValuePair<String, double>[] data = new KeyValuePair<string, double>[] { };
                        ICollection<KeyValuePair<string, double>> collection = new Dictionary<String, double>();
                        for (int v = 0; v <= ds.Tables[0].Rows.Count - 1; v++)
                        {

                            string colX = ds.Tables[0].Rows[v]["ColX"].ToString();
                            double colY = double.Parse(ds.Tables[0].Rows[v]["ColY"].ToString());
                            KeyValuePair<string, double> local = new KeyValuePair<string, double>(colX, colY);
                            collection.Add(local);
                        }

                        data = collection.ToArray();
                        bool isLogarithmic = series[i].IsLogarithmic();

                        Dispatcher.BeginInvoke(delegate
                        {
                            if (int.Parse(chart.GetChartType()) != (int)enmChartType.Pie)
                            {
                                LinearAxis la = new LinearAxis();
                                la.Orientation = AxisOrientation.Y;
                                if (!isLogarithmic)
                                    la.Minimum = 0;

                                newChart.Axes.Add(la);
                            }
                            newSeries.ItemsSource = data;
                            newChart.Series.Add(newSeries);
                            loadseries = true;
                            chartBusy.IsBusy = false;
                            Grid.SetRow(newChart, 0);
                            Grid.SetColumn(newChart, 0);
                            ContentGrid.Children.Add(newChart);
                        });

                        while (!loadseries)
                            Thread.Sleep(10);
                        //this.LayoutRoot.Children.Add(newChart);
                    }

                    else
                    {
                        //chartBusy.IsBusy = false;
                    }

                }

            }
            catch (Exception ex)
            {
                //BusyWindow.IsBusy = false;
                //chartBusy.IsBusy = false;
            }
        }


        List<KeyNamePair> listTab = null;

        public void SetListTab(List<KeyNamePair> _listTab)
        {
            listTab = _listTab;
        }

        int RC_View_ID = 0;
        public void SetRC_View_ID(int _RC_View_ID)
        {
            RC_View_ID = _RC_View_ID;
        }

        int D_Chart_ID = 0;
        public void SetD_Chart_ID(int _D_Chart_ID)
        {
            D_Chart_ID = _D_Chart_ID;
        }

        int _KPI_Pane_ID = 0;
        public void SetKPI_Pane_ID(int KPI_Pane_ID)
        {
            _KPI_Pane_ID = KPI_Pane_ID;
        }


        private void button1_Click(object sender, RoutedEventArgs e)
        {
            this.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        PopupMenu infoWin = null;
        void CreatePanelMenu()
        {
            infoWin = new PopupMenu();

            string menuHeader = "Edit";

            if (rolecenter != null)
            {
                if (rolecenter.IsKPI)
                    menuHeader = "Add/Edit KPI";
            }

            PopupMenuItem mnu = new PopupMenuItem("Images/Editor32.png", Msg.GetMsg(Envs.GetCtx(), menuHeader), null);
            if (menuHeader == "Edit")
            {
                mnu.ImageSource = Envs.LoadImageSource("AddView22.png");
            }
            else
            {
                mnu.ImageSource = Envs.LoadImageSource("EditKPI22.png");
            }
            //mnu.Name = "Edit";
            mnu.Click += new RoutedEventHandler(mnu_Click);
            infoWin.AddItem(mnu);

            if (rolecenter != null)
            {
                if (rolecenter.IsKPI)
                {
                    mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "EditKPIPanel"), null);
                    mnu.ImageSource = Envs.LoadImageSource("EditKPIPane22.png");
                    //mnu.Name = "EditKPIPane";
                    mnu.Click += new RoutedEventHandler(mnukpi_Click);
                    infoWin.AddItem(mnu);

                    mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "RefreshKPI"), null);
                    mnu.ImageSource = Envs.LoadImageSource("ResetCache22.png");
                    
                   // mnu.Name = "RefreshKPI";
                    mnu.Click += new RoutedEventHandler(mnuRefresh_Click);
                    infoWin.AddItem(mnu);
                }
            }

            mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "Zoom"), null);
            mnu.ImageSource = Envs.LoadImageSource("ZoomKPI22.png");
            //mnu.Name = "Zoom";
            mnu.Click += new RoutedEventHandler(mnuZoom_Click);
            infoWin.Items.Add(mnu);

            infoWin.AddSeparator();

            mnu = new PopupMenuItem(null, Msg.GetMsg(Envs.GetCtx(), "DeletePanel"), null);
            mnu.ImageSource = Envs.LoadImageSource("ClosePane22.png");
            //mnu.Name = "Close";
            mnu.Click += new RoutedEventHandler(mnuExit_Click);
            infoWin.Items.Add(mnu);



            infoWin.AddTrigger(TriggerTypes.LeftClick, btnOption);
        }

        void mnuRefresh_Click(object sender, RoutedEventArgs e)
        {
            btnOption.IsEnabled = false;

            BusyIndicator kpibusy = new BusyIndicator();
            kpibusy.Style = Application.Current.Resources["RoundBusyIndicator"] as Style;
            AddControl(kpibusy);
            kpibusy.IsBusy = true;

            RefreshKPI(_KPI_Pane_ID, kpibusy, true, true);
        }

        void mnukpi_Click(object sender, RoutedEventArgs e)
        {
            rolecenter.EditMode = true;
            KPIPane kpipane = new KPIPane(rolecenter);
            kpipane.Show();
        }


        bool isZoom = false;
        int zoomRow = 0;
        int zoomCol = 0;
        int zoomColspan = 0;
        int zoomRowspan = 0;
        Grid _zoom = null;
        void mnuZoom_Click(object sender, RoutedEventArgs e)
        {
            _scrollPanel.Content = null;

            if (isZoom)
            {
                _scrollPanel.Content = null;
                _zoom.Children.Remove(this);
                Grid.SetRow(this, zoomRow);
                Grid.SetColumn(this, zoomCol);
                Grid.SetColumnSpan(this, zoomColspan);
                Grid.SetRowSpan(this, zoomRowspan);
                this.MaxHeight = 220 * zoomRowspan;
                this.MinHeight = 220 * zoomRowspan;
                this.Height = 220 * zoomRowspan;
                RootLayoutGrid.Children.Add(this);
                _scrollPanel.Content = RootLayoutGrid;
                _zoom = null;
                isZoom = false;
            }
            else
            {
                zoomCol = Grid.GetColumn(this);
                zoomRow = Grid.GetRow(this);
                zoomRowspan = Grid.GetRowSpan(this);
                zoomColspan = Grid.GetColumnSpan(this);

                RootLayoutGrid.Children.Remove(this);
                _zoom = new Grid();
                //_zoom.Background = new SolidColorBrush(Colors.Cyan);
                //_zoom.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
                //_zoom.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
                this.MinHeight = 220 * 2;
                //this.Width = _scrollPanel.Width;
                //this.Margin = new Thickness(0, 0, 0, 0);

                Grid.SetRow(this, 0);
                Grid.SetColumn(this, 0);
                _zoom.Children.Add(this);
                isZoom = true;
                _scrollPanel.Content = _zoom;
            }
        }

        void mnuExit_Click(object sender, RoutedEventArgs e)
        {

            if (rolecenter != null)
            {
                ShowMessage.AskMessage("DeleteIt", true, "").Closed += (sa, ea) =>
                {
                    if (true.Equals(((Message)sa).DialogResult))
                    {
                        if (rolecenter.IsKPI)
                        {
                            string[] DelCommand = new string[] 
                    { 
                        "DELETE from RC_TabPanels WHERE rolecenterpanels = 3 AND record_id = " + rolecenter.KPIPaneID ,
                        "DELETE from RC_KPIPane WHERE RC_KPIPane_ID = " + rolecenter.KPIPaneID
                    };

                            BackgroundWorker bgw = new BackgroundWorker();
                            bgw.DoWork += (ov, ev) =>
                            {
                                int delResult = DB.ExecuteQuery(DelCommand[0]);
                                if (delResult > 0)
                                    DB.ExecuteQuery(DelCommand[1]);
                            };

                            bgw.RunWorkerCompleted += (ov, ev) =>
                            {
                                this.Visibility = System.Windows.Visibility.Collapsed;
                                ShowMessage.Info("DeletedKPIPanel", true, "", "");
                            };

                            bgw.RunWorkerAsync();
                        }
                        else if (rolecenter.D_Chart_ID > 0)
                        {
                            int delResult = 0;
                            string[] DelCommand = new string[] 
                    { 
                        "DELETE from RC_TabPanels WHERE rolecenterpanels = 2 AND record_id = " + rolecenter.ChartPane_ID ,
                        "DELETE from RC_ChartPane WHERE RC_ChartPane_ID = " + rolecenter.ChartPane_ID
                    };


                            BackgroundWorker bgw = new BackgroundWorker();
                            bgw.DoWork += (ov, ev) =>
                            {
                                delResult = DB.ExecuteQuery(DelCommand[0]);
                                if (delResult > 0)
                                    delResult = DB.ExecuteQuery(DelCommand[1]);
                            };

                            bgw.RunWorkerCompleted += (ov, ev) =>
                            {
                                this.Visibility = System.Windows.Visibility.Collapsed;
                                ShowMessage.Info("DeletedChartPanel", true, "", "");
                            };

                            bgw.RunWorkerAsync();
                        }
                        else
                        {
                            string[] DelCommand = new string[] 
                    { 
                        "DELETE from RC_TabPanels WHERE rolecenterpanels = 1 AND record_id = " + rolecenter.FramePane_ID ,
                        "DELETE from RC_ViewPane WHERE RC_ViewPane_ID = " + rolecenter.FramePane_ID
                    };

                            BackgroundWorker bgw = new BackgroundWorker();
                            bgw.DoWork += (ov, ev) =>
                            {
                                int delResult = DB.ExecuteQuery(DelCommand[0]);
                                if (delResult > 0)
                                    DB.ExecuteQuery(DelCommand[1]);
                            };

                            bgw.RunWorkerCompleted += (ov, ev) =>
                            {
                                this.Visibility = System.Windows.Visibility.Collapsed;
                                ShowMessage.Info("DeletedViewPanel", true, "", "");
                            };

                            bgw.RunWorkerAsync();
                        }
                    }
                };
            }
        }

        void mnu_Click(object sender, RoutedEventArgs e)
        {
            if (_charts != null)
            {
                rolecenter.EditMode = true;
                AddChartToTab chartPane = new AddChartToTab(rolecenter);
                chartPane.Show();
            }
            else if (_gridController != null)
            {
                rolecenter.EditMode = true;
                FramePane chartPane = new FramePane(rolecenter);
                Utility.Envs.RegisterWindowForm(chartPane);
                chartPane.Show();
            }
            else
            {

                int row = kpigrid.SelectedIndex;
                int data = 0;
                if (row != -1)
                {
                    var type = kpigrid.SelectedItem.GetType();
                    PropertyInfo objPropInfo = type.GetProperty("ID");
                    if (objPropInfo != null)
                    {
                        data = int.Parse(objPropInfo.GetValue(kpigrid.SelectedItem, null).ToString());
                    }
                }
                rolecenter.EditMode = true;
                AddKPI kpi = new AddKPI(_KPI_Pane_ID, data);
                kpi.Show();
            }
        }

        DataTable dt = new DataTable();
        VDataGrid kpigrid = null;

        public void RefreshKPI(int KPI_Pane_ID, BusyIndicator kpibusy, bool refresh, bool newVersion)
        {
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.WorkerReportsProgress = true;

            kpigrid.DataContext = null;
            kpigrid.ItemsSource = null;
            kpigrid.Columns.Clear();

            DataGridTextColumn columnObj = new DataGridTextColumn();
            columnObj.Header = Msg.Translate(Envs.GetCtx(), "ID");
            columnObj.Binding = new System.Windows.Data.Binding("ID");
            columnObj.IsReadOnly = true;
            columnObj.Visibility = System.Windows.Visibility.Collapsed;
            kpigrid.Columns.Add(columnObj);

            DataGridTextColumn keyvalueObj = new DataGridTextColumn();
            keyvalueObj.Header = Msg.Translate(Envs.GetCtx(), "Label");
            keyvalueObj.Binding = new System.Windows.Data.Binding("Label");
            keyvalueObj.IsReadOnly = true;
            kpigrid.Columns.Add(keyvalueObj);

            DataGridTextColumn opNameObj = new DataGridTextColumn();
            opNameObj.Header = Msg.Translate(Envs.GetCtx(), "TotalValue");
            opNameObj.Binding = new System.Windows.Data.Binding("TotalValue");
            opNameObj.IsReadOnly = true;
            kpigrid.Columns.Add(opNameObj);

            Ctx ctx = Envs.GetCtx();
            DataSet dsData = new DataSet();
            Dictionary<string, string> dic = (Dictionary<String, string>)ctx.GetMap();
            bool pass = false;

            bgw.DoWork += (od, vd) =>
                {
                    var client = AEnv.GetDataServiceDBClient();
                    client.ExecuteKPICompleted += (ov, ev) =>
                        {
                            if (ev.Result != null)
                                dsData.FromXml(ev.Result);

                            pass = true;
                        };

                    client.ExecuteKPIAsync(dic, KPI_Pane_ID);
                    client.CloseAsync();

                    while (!pass)
                    {
                        Thread.Sleep(0);
                    }
                };


            bgw.RunWorkerCompleted += (ov, ev) =>
                {
                    if (dsData != null)
                    {
                        if (dsData.Tables.Count > 0)
                        {
                            kpigrid.ItemsSource = null;
                            kpigrid.DataContext = null;
                            kpigrid.ItemsSource = dsData.Tables[0].GetBindableData(new Connector());

                            kpigrid.Columns[0].Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }

                    ContentGrid.Children.Remove(kpibusy);

                    if(!ContentGrid.Children.Contains(kpigrid))
                        ContentGrid.Children.Add(kpigrid);
                    
                    btnOption.IsEnabled = true;
                };

            bgw.RunWorkerAsync();
        }

        public void RefreshKPI(int KPI_Pane_ID, BusyIndicator kpibusy, bool refresh)
        {
            DataSet dsData = new DataSet();
            BackgroundWorker bgw = new BackgroundWorker();
            bgw.WorkerReportsProgress = true;

            kpigrid.DataContext = null;
            kpigrid.ItemsSource = null;
            kpigrid.Columns.Clear();

            DataGridTextColumn columnObj = new DataGridTextColumn();
            columnObj.Header = Msg.Translate(Envs.GetCtx(), "ID");
            columnObj.Binding = new System.Windows.Data.Binding("ID");
            columnObj.IsReadOnly = true;
            columnObj.Visibility = System.Windows.Visibility.Collapsed;
            kpigrid.Columns.Add(columnObj);

            DataGridTextColumn keyvalueObj = new DataGridTextColumn();
            keyvalueObj.Header = Msg.Translate(Envs.GetCtx(), "Label");
            keyvalueObj.Binding = new System.Windows.Data.Binding("Label");
            keyvalueObj.IsReadOnly = true;
            kpigrid.Columns.Add(keyvalueObj);

            DataGridTextColumn opNameObj = new DataGridTextColumn();
            opNameObj.Header = Msg.Translate(Envs.GetCtx(), "TotalValue");
            opNameObj.Binding = new System.Windows.Data.Binding("TotalValue");
            opNameObj.IsReadOnly = true;
            kpigrid.Columns.Add(opNameObj);

            bgw.DoWork += (o, e) =>
            {
                //string sql = "Select Name, RC_KPI_ID, RC_KPICenter_ID from RC_KPICenter WHERE (" + Envs.GetCtx().GetAD_User_ID() + " IN ( Select AD_User_ID from RC_KPIAccess inn Where inn.RC_KPI_ID = RC_KPI_ID ) OR " + Envs.GetCtx().GetAD_Role_ID() + " IN (Select AD_Role_ID from RC_KPIAccess innn Where innn.RC_KPI_ID = RC_KPI_ID )) AND IsActive = 'Y' Order By SeqNo";
                string sql = @"Select center.Name, kpi.RC_KPI_ID, center.RC_KPICenter_ID FROM RC_KPI kpi INNER JOIN RC_KPICenter center ON kpi.RC_KPI_ID = center.RC_KPI_ID INNER JOIN RC_KPIAccess acc ON center.RC_KPI_ID = acc.RC_KPI_ID WHERE kpi.IsActive = 'Y' AND ( (acc.AD_User_ID = " + Envs.GetCtx().GetAD_User_ID() + ") OR ( acc.AD_Role_ID = " + Envs.GetCtx().GetAD_Role_ID() + ") ) AND center.RC_KPIPane_ID = " + KPI_Pane_ID + "  ORDER BY center.SeqNo ";
                IDataReader dr = DB.ExecuteReader(sql);

                int iRCKPIID = 0;
                string kpiName = "";

                while (dr.Read())
                {
                    StringBuilder sQuery = new StringBuilder();
                    iRCKPIID = int.Parse(dr[1].ToString());
                    kpiName = dr[0].ToString();


                    X_RC_KPI xkpi = new X_RC_KPI(Envs.GetCtx(), iRCKPIID, null);
                    sQuery.Append("Select '").Append(kpiName)
                        .Append("' AS Label, coalesce(");

                    if (xkpi.IsSum())
                        sQuery.Append("SUM(");
                    else if (xkpi.IsCount())
                        sQuery.Append("COUNT(");
                    else if (xkpi.IsMinimum())
                        sQuery.Append("MIN(");
                    else if (xkpi.IsMaximum())
                        sQuery.Append("MAX(");

                    MColumn column = MColumn.Get(Envs.GetCtx(), xkpi.GetAD_Column_ID());
                    sQuery.Append(column.GetColumnName())
                        .Append("), 0) AS Value ");

                    string tableName = MTable.Get(Envs.GetCtx(), column.GetAD_Table_ID()).GetTableName();
                    sQuery.Append("From ")
                        .Append(tableName);

                    sQuery.Append(" WHERE IsActive = 'Y' AND ");

                    int tabid = xkpi.GetAD_Tab_ID();
                    /** Window No					*/
                    int _windowNo = Envs.CreateWindowNo(this);
                    MTab tab = MTab.Get(Envs.GetCtx(), tabid);

                    int AD_Window_ID = tab.GetAD_Window_ID();
                    GridWindowVO wVO = AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);
                    if (wVO == null)
                    {
                        //do something.
                    }
                    GridWindow _mWindow = new GridWindow(wVO);
                    GridTab _mTab = _mWindow.GetTabByID(tabid);
                    GridField[] findFields = _mTab.GetFields();

                    MUserQuery obj = new MUserQuery(Envs.GetContext(), xkpi.GetAD_UserQuery_ID(), null);
                    DataSet ds = obj.GetQueryLines();
                    Query _query = GetQueryAdvanced(ds, tableName, findFields);

                    sQuery.Append(_query.GetWhereClause(true));
                    string tabWhere = _mTab.GetWhereClause();
                    if (tabWhere.Trim().Length > 0)
                        sQuery.Append(" AND ").Append(tabWhere);
                    string finalSQL = MRole.GetDefault(Envs.GetCtx(), false).AddAccessSQL(sQuery.ToString(), _mTab.GetTableName(), MRole.SQL_FULLYQUALIFIED, MRole.SQL_RO);

                    if (dsData.Tables.Count == 0)
                    {
                        DataColumn dc;
                        dc = new DataColumn("ID");
                        dt.Columns.Add(dc);

                        dc = new DataColumn("Label");
                        dt.Columns.Add(dc);

                        dc = new DataColumn("TotalValue");
                        dt.Columns.Add(dc);

                        dsData.Tables.Add(dt);
                        dsData.Tables[0].Rows.Clear();
                    }

                    IDataReader d = DB.ExecuteReader(finalSQL);

                    while (d.Read())
                    {
                        DataRow datarow = dsData.Tables[0].NewRow();
                        datarow[0] = int.Parse(dr["RC_KPICenter_ID"].ToString());
                        datarow[1] = d[0].ToString();
                        datarow[2] = double.Parse(d[1].ToString());

                        dsData.Tables[0].Rows.Add(datarow);
                        bgw.ReportProgress(0);
                    }
                    d.Close();
                }
                dr.Close();

            };


            bgw.ProgressChanged += (ov, ev) =>
            {
                if (dsData != null)
                {
                    if (dsData.Tables.Count > 0)
                    {
                        kpigrid.ItemsSource = null;
                        kpigrid.DataContext = null;
                        kpigrid.ItemsSource = dsData.Tables[0].GetBindableData(new Connector());
                        kpigrid.Columns[0].Visibility = System.Windows.Visibility.Collapsed;
                        refresh = ContentGrid.Children.Contains(kpigrid);

                        if (!refresh)
                        {
                            Grid.SetRow(kpigrid, 0);
                            Grid.SetColumn(kpigrid, 0);
                            ContentGrid.Children.Add(kpigrid);

                            ContentGrid.Children.Remove(kpibusy);
                            Grid.SetRow(kpibusy, 0);
                            Grid.SetColumn(kpibusy, 0);
                            grid2.Children.Add(kpibusy);
                        }
                        else
                        {
                            refresh = grid2.Children.Contains(kpibusy);
                            if (!refresh)
                            {
                                ContentGrid.Children.Remove(kpibusy);

                                ContentGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
                                ContentGrid.RowDefinitions[1].Height = new GridLength(20, GridUnitType.Pixel);
                                grid2.Visibility = System.Windows.Visibility.Visible;

                                Grid.SetRow(kpibusy, 0);
                                Grid.SetColumn(kpibusy, 0);
                                grid2.Children.Add(kpibusy);
                            }

                        }
                    }
                }
            };


            bgw.RunWorkerCompleted += (o, e) =>
            {
                btnOption.IsEnabled = true;
                kpibusy.IsBusy = false;
                grid2.Children.Remove(kpibusy);

                ContentGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
                ContentGrid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
                grid2.Visibility = System.Windows.Visibility.Collapsed;

            };

            bgw.RunWorkerAsync();
        }

        public static SolidColorBrush GetColorFromHexa(string hexaColor)
        {
            return new SolidColorBrush(
                Color.FromArgb(
                    Convert.ToByte(hexaColor.Substring(1, 2), 16),
                    Convert.ToByte(hexaColor.Substring(3, 2), 16),
                    Convert.ToByte(hexaColor.Substring(5, 2), 16),
                    Convert.ToByte(hexaColor.Substring(7, 2), 16)
                )
            );
        }

        public void ADdKPI(int KPI_Pane_ID)
        {
            //ContentGrid.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
            //ContentGrid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Pixel);
            //grid2.Visibility = System.Windows.Visibility.Collapsed;

            btnOption.IsEnabled = false;
            bPrev.Visibility = System.Windows.Visibility.Collapsed;
            btnNext.Visibility = System.Windows.Visibility.Collapsed;
            BusyIndicator kpibusy = new BusyIndicator();
            kpibusy.Style =  Application.Current.Resources["RoundBusyIndicator"] as Style;
            AddControl(kpibusy);
            kpibusy.IsBusy = true;

            //AddControl(kpibusy);


            kpigrid = new VDataGrid();
            //kpibusy.Background = new SolidColorBrush(Colors.White);

            kpigrid.ColumnHeaderStyle = Application.Current.Resources["DataGridColumnHeaderStyleSL"] as Style;
            kpigrid.RowHeaderStyle = Application.Current.Resources["DataGridRowHeaderStyleSL"] as Style;
            kpigrid.AlternatingRowBackground = new SolidColorBrush(Colors.White);
            kpigrid.ColumnHeaderHeight = 25;
            kpigrid.RowHeight = 23;
            kpigrid.BorderThickness = new Thickness(0);
            kpigrid.BorderBrush = new SolidColorBrush(Colors.DarkGray);
            kpigrid.MinColumnWidth = 100;
            kpigrid.ColumnWidth = new DataGridLength(1, DataGridLengthUnitType.SizeToCells);
            kpigrid.GridLinesVisibility = DataGridGridLinesVisibility.None;
            kpigrid.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;

            //kpigrid.AlternatingRowBackground = new SolidColorBrush(Envs.GetColorFromHexString("#eaeaea"));
            //kpigrid.Foreground = new SolidColorBrush(Envs.GetColorFromHexString("#595959"));
            //kpigrid.Background = new SolidColorBrush(Envs.GetColorFromHexString("#f6f8fa"));


            //kpigrid.RowBackground = new SolidColorBrush(Colors.White);
            //kpigrid.ShowRowNumber = true;
            kpigrid.IsReadOnly = true;
            kpigrid.SupressRowPaint = true;
            kpigrid.AutoGenerateColumns = false;
            kpigrid.ItemsSource = null;
            kpigrid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(kpigrid_AutoGeneratingColumn);

            RefreshKPI(KPI_Pane_ID, kpibusy, false, true);

            //DataSet dsData = new DataSet();
            //BackgroundWorker bgw = new BackgroundWorker();



            //bgw.DoWork += (o, e) =>
            //    {
            //        string sql = "Select Name, RC_KPI_ID, RC_KPICenter_ID from RC_KPICenter WHERE (" + Envs.GetCtx().GetAD_User_ID() + " IN ( Select AD_User_ID from RC_KPIAccess inn Where inn.RC_KPI_ID = RC_KPI_ID ) OR " + Envs.GetCtx().GetAD_Role_ID() + " IN (Select AD_Role_ID from RC_KPIAccess innn Where innn.RC_KPI_ID = RC_KPI_ID )) AND IsActive = 'Y' Order By SeqNo";
            //        IDataReader dr = DB.ExecuteReader(sql);

            //        int iRCKPIID = 0;
            //        string kpiName = "";

            //        while (dr.Read())
            //        {
            //            StringBuilder sQuery = new StringBuilder();
            //            iRCKPIID = int.Parse(dr[1].ToString());
            //            kpiName = dr[0].ToString();


            //            X_RC_KPI xkpi = new X_RC_KPI(Envs.GetCtx(), iRCKPIID, null);
            //            sQuery.Append("Select '").Append(kpiName)
            //                .Append("' AS Label, coalesce(");

            //            if (xkpi.IsSum())
            //                sQuery.Append("SUM(");
            //            else if (xkpi.IsCount())
            //                sQuery.Append("COUNT(");
            //            else if (xkpi.IsMinimum())
            //                sQuery.Append("MIN(");
            //            else if (xkpi.IsMaximum())
            //                sQuery.Append("MAX(");

            //            MColumn column = MColumn.Get(Envs.GetCtx(), xkpi.GetAD_Column_ID());
            //            sQuery.Append(column.GetColumnName())
            //                .Append("), 0) AS Value ");

            //            string tableName = MTable.Get(Envs.GetCtx(), column.GetAD_Table_ID()).GetTableName();
            //            sQuery.Append("From ")
            //                .Append(tableName);

            //            sQuery.Append(" Where IsActive = 'Y' AND ");

            //            int tabid = xkpi.GetAD_Tab_ID();
            //            /** Window No					*/
            //            int _windowNo = Envs.CreateWindowNo(this);
            //            MTab tab = MTab.Get(Envs.GetCtx(), tabid);

            //            int AD_Window_ID = tab.GetAD_Window_ID();
            //            GridWindowVO wVO = AEnv.GetMWindowVO(_windowNo, AD_Window_ID, 0);
            //            if (wVO == null)
            //            {
            //                //do something.
            //            }
            //            GridWindow _mWindow = new GridWindow(wVO);
            //            GridTab _mTab = _mWindow.GetTabByID(tabid);
            //            GridField[] findFields = _mTab.GetFields();

            //            MUserQuery obj = new MUserQuery(Envs.GetContext(), xkpi.GetAD_UserQuery_ID(), null);
            //            DataSet ds = obj.GetQueryLines();
            //            Query _query = GetQueryAdvanced(ds, tableName, findFields);

            //            sQuery.Append(_query.GetWhereClause(true));

            //            if (dsData.Tables.Count == 0)
            //            {
            //                DataColumn dc;
            //                dc = new DataColumn("ID");
            //                dt.Columns.Add(dc); 

            //                dc = new DataColumn("Label");
            //                dt.Columns.Add(dc);

            //                dc = new DataColumn("Value");
            //                dt.Columns.Add(dc);

            //                dsData.Tables.Add(dt);
            //            }

            //            IDataReader d = DB.ExecuteReader(sQuery.ToString());

            //            while (d.Read())
            //            {
            //                DataRow datarow = dsData.Tables[0].NewRow();
            //                datarow[0] = int.Parse(dr["RC_KPICenter_ID"].ToString());
            //                datarow[1] = d[0].ToString();
            //                datarow[2] = double.Parse(d[1].ToString());


            //                dsData.Tables[0].Rows.Add(datarow);
            //            }
            //            d.Close();
            //        }
            //        dr.Close();

            //    };


            //bgw.RunWorkerCompleted += (o, e) =>
            //    {
            //        if (dsData != null)
            //        {
            //            if (dsData.Tables.Count > 0)
            //            {
            //                kpigrid.ItemsSource = null;
            //                kpigrid.DataContext = null;

            //                kpigrid.ItemsSource = dsData.Tables[0].GetBindableData(new Connector());
            //                Grid.SetRow(kpigrid, 0);
            //                Grid.SetColumn(kpigrid, 0);
            //                ContentGrid.Children.Add(kpigrid);

            //            }
            //        }

            //        kpibusy.IsBusy = false;

            //    };

            //bgw.RunWorkerAsync();

            //kpibusy.IsBusy = false;


        }

        void kpigrid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            DataGrid dg = (sender as DataGrid);
            foreach (DataGridColumn col in dg.Columns)
            {
                if (col.DisplayIndex == 1)
                    col.Width = new DataGridLength(140);

                if (col.DisplayIndex == 0)
                {
                    col.Visibility = Visibility.Collapsed;
                }
            }
        }

        private Object ParseValue(GridField field, object pp)
        {
            if (pp == null)
                return null;
            int dt = field.GetDisplayType();
            String inStr = pp.ToString();
            if (inStr == null || inStr.Equals(Null.NULLString) || inStr == "")
                return null;
            try
            {
                //	Return Integer
                if (dt == DisplayType.Integer
                    || (DisplayType.IsID(dt) && field.GetColumnName().EndsWith("_ID")))
                {
                    int i = int.Parse(inStr);
                    return i;
                }
                //	Return BigDecimal
                else if (DisplayType.IsNumeric(dt))
                {
                    return Decimal.Parse(inStr);       //DisplayType.GetNumberFormat(dt).GetFormatedValue(inStr);
                }
                //	Return Timestamp
                else if (DisplayType.IsDate(dt))
                {
                    String time = "";
                    try
                    {
                        return DateTime.Parse(inStr);
                    }
                    catch (Exception e)
                    {
                        //log.Log(Level.WARNING, inStr + "(" + inStr.GetType().FullName + ")" + e);
                        time = DisplayType.GetDateFormat(dt).Format(inStr);
                    }
                    try
                    {
                        return DateTime.Parse(time);
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch (Exception ex)
            {
                //log.Log(Level.WARNING, "Object=" + inStr, ex);
                String error = ex.Message;
                if (error == null || error.Length == 0)
                    error = ex.ToString();
                StringBuilder errMsg = new StringBuilder();
                errMsg.Append(field.GetColumnName()).Append(" = ").Append(inStr).Append(" - ").Append(error);
                //
                ShowMessage.Error("ValidationError", true, errMsg.ToString());
                return null;
            }

            return inStr;
        }	//	parseValue

        private GridField GetTargetMField(GridField[] _findFields, string columnName)
        {
            // if no column name, then return null
            if (columnName == null)
                return null;
            // else find field for the given column
            for (int c = 0; c < _findFields.Length; c++)
            {
                GridField field = _findFields[c];
                if (columnName.Equals(field.GetColumnName()))
                    return field;
            }
            return null;
        }


        private Query GetQueryAdvanced(DataSet dsAdvanceData, String _tableName, GridField[] gridField)
        {
            Query query = new Query(_tableName);
            // check if dataset have any table
            if (dsAdvanceData.Tables.Count == 1)
            {
                // for every row in dataset
                for (int i = 0; i < dsAdvanceData.Tables[0].Rows.Count; i++)
                {
                    DataRow dtRowObj = dsAdvanceData.Tables[0].Rows[i];
                    //	Column
                    string infoName = dtRowObj["KEYNAME"].ToString();
                    string columnName = dtRowObj["KEYVALUE"].ToString();
                    GridField field = GetTargetMField(gridField, columnName);
                    string columnSQL = field.GetColumnSQL(); //
                    //	Operator
                    string optr = dtRowObj["OPERATORNAME"].ToString(); //dtRowObj["OPERATOR"].ToString()
                    //	Value

                    object value = dtRowObj["VALUE1VALUE"];
                    object parsedValue = ParseValue(field, value);
                    //string infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    String infoDisplay = null;

                    if (value == null || value.ToString().Length < 1)
                    {
                        if (Query.BETWEEN.Equals(optr))
                            continue;	//	no null in between
                        parsedValue = Null.NULLString;
                        infoDisplay = "NULL";
                    }
                    else
                    {
                        infoDisplay = dtRowObj["VALUE1NAME"].ToString();
                    }

                    //	Value2
                    // if "BETWEEN" selected
                    if (Query.BETWEEN.Equals(optr))
                    {

                        object value2 = dtRowObj["VALUE2VALUE"].ToString();
                        if (value2 == null || value2.ToString().Trim().Length < 1)
                            continue;

                        Object parsedValue2 = ParseValue(field, value2);
                        string infoDisplay_to = dtRowObj["VALUE2NAME"].ToString();
                        if (parsedValue2 == null)
                            continue;
                        // else add restriction where clause to query with between operator
                        query.AddRangeRestriction(columnSQL, parsedValue, parsedValue2, infoName,
                            infoDisplay, infoDisplay_to);
                    }
                    else
                    {
                        // else add simple restriction where clause to query
                        query.AddRestriction(columnSQL, optr, parsedValue, infoName, infoDisplay);
                    }
                }
            }
            return query;
        }

        private void btnZoom_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
